package com.training.bt.user.service;

import com.training.bt.entity.User;
import com.training.bt.enums.Role;
import com.training.bt.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional
public class UserExperienceServiceImpl implements UserExperienceService {

    private final UserMapper userMapper;

    public UserExperienceServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User addExperience(Long userId, long experience) {
        Optional<User> userOptional = Optional.ofNullable(userMapper.selectById(userId));
        return userOptional.map(user -> {
            // 增加经验值
            user.setExperience(user.getExperience() + experience);

            // 检查是否需要升级
            Role newRole = checkRoleUpgrade(user);
            if (newRole != user.getRole()) {
                user.setRole(newRole);
            }

            // 更新用户信息
            userMapper.updateById(user);
            return user;
        }).orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    @Override
    public Role checkRoleUpgrade(User user) {
        long experience = user.getExperience();
        Role currentRole = user.getRole();

        if (experience >= 1 && currentRole == Role.LEVEL_1) {
            return Role.LEVEL_2;
        } else if (experience >= 10 && currentRole == Role.LEVEL_2) {
            return Role.LEVEL_3;
        } else if (experience >= 100 && currentRole == Role.LEVEL_3) {
            return Role.LEVEL_4;
        }
        return currentRole;
    }
}